var _$ = CC = {};

$.extend($,{
    cc:CC
});

function getTopWindow(){
    var topWin=window;
    while(topWin.parent != topWin && isNotEmpty(topWin.parent.CC)){
        topWin = topWin.parent;
    }
    return topWin;
}

var notify = {};
$.extend(notify,{
    'notify':function(type,option){
        var opts = {
            position: 'top right',
            title:"提示"
        };
        if(isString(option)){
            opts["msg"] = option;
            Lobibox.notify(type,opts);
        }else{
           var options = $.extend(opts,option);
            Lobibox.notify(type,options);
        }

    },
    'info':function(option){
        this.notify("info",option);
    },
    'warning':function(option){
        this.notify("warning",option);
    },
    'error':function(option){
        this.notify("error",option);
    },
    'success':function(option){
        this.notify("success",option);
    }
});
$.extend(_$,{
    "notify":notify
});
$(document).ajaxSend(function(){
    if(isEmpty(window._PATH_LOAD_SUCCESS_) || window._PATH_LOAD_SUCCESS_){
        $('body').showLoading();
    }
}).ajaxSuccess(function(event,xhr,settrings){
    $('body').hideLoading();
}).ajaxError(function(event,xhr,settings){
    $('body').hideLoading();
    var httpStatus = xhr.status;
    $.cc.ajaxErrorHander(httpStatus);
});

$.extend(_$,{
layer:getTopWindow().layer,
    message:function(msg,callback,options){
        var _this =  this;

        _this.layer.alert(msg,options,function(index){
            if(callback){
                callback.call(null);
            }
            _this.layer.close(index);
        });
    },
    alert:function(){
        var _this =  this;
        var msg = arguments[0];
        var callback = isNotEmpty(arguments[1]) && isFunction(arguments[1])?arguments[1]:arguments[2];
        var options = isNotEmpty(arguments[1]) && !isFunction(arguments[1])?arguments[1]:arguments[2];
        var opts = {
            icon:6,
            title:'提示信息',
            offset:"30%"
        };
        $.extend(true,opts,options);
         _this.message(msg,callback,opts);
    },
    warn:function(){
        var _this =  this;
        var msg = arguments[0];
        var callback = isNotEmpty(arguments[1]) && isFunction(arguments[1])?arguments[1]:arguments[2];
        var options = isNotEmpty(arguments[1]) && !isFunction(arguments[1])?arguments[1]:arguments[2];
        var opts = {
            icon: 0,
            title:'警告信息',
            offset:"30%"
        };
        $.extend(true,opts,options);
        _this.message(msg,callback,opts);
    },
    error:function(){
        var _this =  this;
        var msg = arguments[0];
        var callback = isNotEmpty(arguments[1]) && isFunction(arguments[1])?arguments[1]:arguments[2];
        var options = isNotEmpty(arguments[1]) && !isFunction(arguments[1])?arguments[1]:arguments[2];
        var opts = {
            icon: 5,
            title:'错误信息',
            offset:"30%"
        };
        $.extend(true,opts,options);
        _this.message(msg,callback,opts);
    },
    close:function(index){
        var _this =  this;
        _this.layer.close(index);
    },
    confirm : function(msg,callbackOk,callbackCancel,options){
        var _this =  this;
        var opts = {
            icon: 3,
            title:'请选择',
            offset:"30%"
        };
        $.extend(true,opts,options);
        _this.layer.confirm(msg, opts, function(index){
            if(callbackOk){
                callbackOk.call(null);
            }
            _this.layer.close(index);
        }, function(index){
            if(callbackCancel){
                callbackCancel.call(null);
            }
            _this.layer.close(index);
        });
    },
    prompt:function(value,callback,options){
        var _this =  this;
        var opts = {
            title:'请输入',
            offset:"30%",
            formType:0
        };
        $.extend(true,opts,options);
        if(isNotEmpty(value)){
            opts["value"] = value;
        }
        _this.layer.prompt(opts,function(ok){
            if(callback){
                callback.call(null,ok);
            }
        });
    },
    tips:function(msg,selector,options){
        var _this =  this;
        var opts = {
            tips: [1, '#3595CC'],
            time: 4000
        };
        $.extend(opts,options);
        _this.layer.tips(msg,selector,opts);
    },
    load:function(type){
        var _this =  this;
        return _this.layer.load(type, {shade: 0.3,time:10*1000});
    },
    open:function(options){
        var _this =  this;
        var defaultConfig ={
            type : 2, //page层
            area : [  '1100px', "600px" ],
            offset: [ '50px'],
            shadeClose:false,
            maxmin : true,
            shade : 0.2, //遮罩透明度
            moveType : 1, //拖拽风格，0是默认，1是传统拖动
            success: function(layero, index){
                var win = getTopWindow();
                var iframeWin = win[layero.find('iframe')[0]['name']];
                iframeWin['p_Win'] = window;
                iframeWin['p_index'] = index;
            }
        };
        var opts = $.extend(true,defaultConfig,options);
        _this.layer.open(opts);
    },
    ajaxErrorHander:function(httpStatus,status){
        if("timeout" == status){
            _$.notify.error({
                "title":"timeout",
                "msg":"服务器繁忙,请稍后重试"
            });
            return;
        }

        if(httpStatus == 403){
            _$.notify.error({
                "title":403,
                "msg":"资源不可用"
            });
            return;
        }
        if(httpStatus == 404){
            _$.notify.error({
                "title":404,
                "msg":"无法找到指定位置的资源"
            });
            return;
        }
        if(httpStatus == 405){
            _$.notify.error({
                "title":405,
                "msg":"请求方法（GET、POST）类型对指定的资源不适用"
            });
            return;
        }
        if(httpStatus == 500){
            _$.notify.error("服务器内部错误,联系管理员");
            return;
        }
        if(httpStatus == 502){
            _$.notify.error("服务器由于维护或者负载过重未能应答");
            return;
        }
    },
    ajaxDtoRequestSync:function(inParams,options){
        var opt = {
            type: "POST",
            beforeSend:function(){
                return true;
            },
            contentType:'application/x-www-form-urlencoded',
            dataType : 'text',
            successHandler:function(result){
            }
        };

        $.extend(opt,options);
        var url = opt.url;
        var type = opt.type;
        var data = {
            "param":inParams.toJSONString()
        };
        var dataType = opt.dataType;
        var contentType = opt.contentType;
        var beforeSend = opt.beforeSend;
        var successHandler = opt.successHandler;
        var succFailHandler = opt.succFailHandler;
        var res;
        if(isEmpty(url)){
            return;
        }
        $.ajax({
            type: type,
            url:url,
            data: data,
            dataType: dataType,
            contentType: contentType,
            timeout:60000,
            async : false,
            beforeSend: beforeSend,
            success: function (responseText) {
                var result = JSonDtoModel.restore(responseText);

                var state = result.getState();
                var info = result.getInfo();
                if(state == 0){
                    res =  successHandler.call(window,result);
                }else{
                    if(isEmpty(info)){
                        _$.notify.error("空指针");
                    } else{
                        //succFailHandler.call(window,result);
                        successHandler.call(window,result);
                    }
                }
            }
        });
        return res;
    },
    ajaxDtoRequestSyncCommon:function(options){
        var callback;
        var opts = {
            url:"",
            successHandler:function(result){
                if(callback){
                    callback.call(null,result);
                }
            }
        };
        $.extend(opts,options);

        var route = opts.route;
        var data = opts.data;
        var url = opts.url;
        callback = opts.callback;

        var inParams = new JSonDtoModel();
        inParams.setParams(data);
        var apiServer=route['apiServer'];
        var call=route['call'];
        var description=route['description'];
        inParams.setRoute(apiServer,call,description);

        var config = {
            url:url,
            successHandler:callback
        };
        return  $.cc.ajaxDtoRequestSync(inParams,config);
    },
    ajaxDtoRequest:function(inParams,options){
        var opt = {
            type: "POST",
            beforeSend:function(){
                return true;
            },
            contentType:'application/x-www-form-urlencoded',
            dataType : 'text',
            successHandler:function(result){
            }
        };

        $.extend(opt,options);
        var url = opt.url;
        var type = opt.type;
        var data = {
            "param":inParams.toJSONString()
        };
        var dataType = opt.dataType;
        var contentType = opt.contentType;
        var beforeSend = opt.beforeSend;
        var successHandler = opt.successHandler;
        var succFailHandler = opt.succFailHandler;
        var res=0;
        if(isEmpty(url)){
            return;
        }
       return  $.ajax({
            type: type,
            url:url,
            data: data,
            dataType: dataType,
            contentType: contentType,
            timeout:60000,
            async : true,
            beforeSend: beforeSend,
            success: function (responseText) {
                var result = JSonDtoModel.restore(responseText);

                var state = result.getState();
                var info = result.getInfo();

                if(state == 0){
                    successHandler.call(window,result);
                }else{
                    if(isEmpty(info)){
                        _$.notify.error("空指针");
                    } else{
                        //succFailHandler.call(window,result);
                        successHandler.call(window,result);
                    }
                }
            }
        });
    },
    ajaxDtoRequestCommon:function(options){
        var callback;
        var opts = {
            url:"",
            successHandler:function(result){
                if(callback){
                    callback.call(null,result);
                }
            }
        };
        $.extend(opts,options);

        var route = opts.route;
        var data = opts.data;
        var url = opts.url;
         callback = opts.callback;

        var inParams = new JSonDtoModel();
        inParams.setParams(data);
        var apiServer=route['apiServer'];
        var call=route['call'];
        var description=route['description'];
        inParams.setRoute(apiServer,call,description);

        var config = {
            url:url,
            successHandler:callback
        };
      return  $.cc.ajaxDtoRequest(inParams,config);
    }
});